﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Model.ModelsExt;
using AntUnion.FrameWork.Util;
using AntUnion.FrameWork.Web.IService;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Json;
using System.Reflection;

namespace AntUnion.FrameWork.Web.Service
{
    /// <summary>
    /// CRM相关业务类
    /// </summary>
    public class CrmService : ICrmService
    {

        /// <summary>
        ///  CRM账户登录验证
        /// </summary>
        /// <param name="login"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public CrmUser GetCrmUser(string login, string password, string ip = "")
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    CrmUser crmUser = mtContext.CrmUsers.FirstOrDefault(k => k.LoginName == login && k.LoginPwd == password && k.Isdel == 0);
                    if (crmUser != null)
                    {
                        crmUser.LastIp = ip;
                        crmUser.LastTime = DateTime.Now;
                        mtContext.SaveChanges();
                    }
                    return crmUser;
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        /// <summary>
        ///  根据账户获取信息
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        public CrmUser GetCrmUser(int id)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    CrmUser crmUser = mtContext.CrmUsers.FirstOrDefault(k => k.Id == id && k.Isdel == 0);
                    return crmUser;
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        /// <summary>
        ///  根据账户获取信息
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        public CrmUser GetCrmUser(string login)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    CrmUser crmUser = mtContext.CrmUsers.FirstOrDefault(k => k.LoginName == login && k.Isdel == 0);
                    return crmUser;
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        /// <summary>
        ///  注册CRM账户
        /// </summary>
        /// <param name="login"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public int AddCrmUser(string login, string password, uint group, int up, Source source)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    //添加账户
                    CrmUser crmUser = new CrmUser()
                    {
                        LoginName = login,
                        LoginPwd = password,
                        Email = login,
                        Creator = Creater.System.ToString(),
                        CreateDate = DateTime.Now,
                        State = 1,
                        Isdel = 0,
                        Pid = 0,
                        Level = 0,
                        CrmGroup = group,
                        CrmUp = up,
                        Source = (int)source
                    };
                    mtContext.CrmUsers.Add(crmUser);
                    mtContext.SaveChanges();
                    if (crmUser.Id != 0)
                    {
                        //添加钱包
#pragma warning disable CS0078 // “l”后缀容易与数字“1”混淆；为清楚起见，请使用“L”
                        CrmWallet crmWallet = new CrmWallet()
                        {
                            Id = Guid.NewGuid().ToString(),
                            CrmId = crmUser.Id,
                            Balance = 0l,
                            Currency = Currency.USD.ToString(),
                            CreateDate = DateTime.Now,
                        };
#pragma warning restore CS0078 // “l”后缀容易与数字“1”混淆；为清楚起见，请使用“L”
                        mtContext.CrmWallets.Add(crmWallet);
                        TbUserRole tbUserRole = new TbUserRole()
                        {
                            UserId = crmUser.Id,
                            RoleId = 40,
                            UserType = (int)UserType.CrmUser
                        };
                        mtContext.TbUserRoles.Add(tbUserRole);
                    }
                    int count = mtContext.SaveChanges();
                    return count;
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 获取CRM钱包信息
        /// </summary>
        /// <param name="crmId"></param>
        /// <returns></returns>
        public List<CrmWallet> GetCrmWallet(int crmId)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    List<CrmWallet> crmWallets = mtContext.CrmWallets.AsNoTracking().Where(k => k.CrmId == crmId).ToList();
                    return crmWallets;
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        /// <summary>
        ///  创建CRM钱包
        /// </summary>
        /// <param name="crmId"></param>
        /// <returns></returns>
        public int AddCrmWallet(int crmId)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    //添加钱包
#pragma warning disable CS0078 // “l”后缀容易与数字“1”混淆；为清楚起见，请使用“L”
                    CrmWallet crmWallet = new CrmWallet()
                    {
                        CrmId = crmId,
                        Balance = 0l,
                        Currency = Currency.USD.ToString(),
                        CreateDate = DateTime.Now,
                    };
#pragma warning restore CS0078 // “l”后缀容易与数字“1”混淆；为清楚起见，请使用“L”
                    int count = mtContext.SaveChanges();
                    return count;
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 获取CRM用户规则
        /// </summary>
        /// <param name="crmuserInfoType"></param>
        /// <returns></returns>
        public List<CrmKyc> GetCrmKyc()
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    List<CrmKyc> crmKycs = mtContext.CrmKycs.AsNoTracking().Where(k => k.State == (int)State.Enable).OrderBy(k => k.Sort).ToList();
                    return crmKycs;
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 获取CRM用户规则
        /// </summary>
        /// <param name="crmuserInfoType"></param>
        /// <returns></returns>
        public List<CrmKyc> GetCrmKyc(int? crmuserInfoType)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    var data = mtContext.CrmKycs.Where(k => k.State == (int)State.Enable).AsQueryable();
                    if (crmuserInfoType != null)
                    {
                        data = data.Where(k => k.Infotype == crmuserInfoType);
                    }
                    List<CrmKyc> crmKycs = data.OrderBy(k => k.Sort).ToList();
                    return crmKycs;
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 获取用户信息审核数据
        /// </summary>
        /// <param name="crmId"></param>
        /// <param name="crmuserInfoType"></param>
        /// <returns></returns>
        public List<CrmUserInfo> GetCrmUserInfo(int crmId)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    List<CrmUserInfo> crmUserInfos = mtContext.CrmUserInfos.AsNoTracking().Where(k => k.CrmId == crmId).ToList();
                    return crmUserInfos;
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 查询是否有待审核记录
        /// </summary>
        /// <param name="crmId"></param>
        /// <param name="crmuserInfoType"></param>
        /// <returns></returns>
        public CrmUserInfo GetCrmUserInfo(int crmId, int crmuserInfoType)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    CrmUserInfo crmUserInfo = mtContext.CrmUserInfos.AsNoTracking().FirstOrDefault(k => k.CrmId == crmId && k.Type == crmuserInfoType && k.State == 0);
                    return crmUserInfo;
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 查询是否有待审核记录
        /// </summary>
        /// <param name="crmId"></param>
        /// <param name="crmuserInfoType"></param>
        /// <returns></returns>
        public CrmUserInfo GetFinancial(int crmId)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    CrmUserInfo crmUserInfo = mtContext.CrmUserInfos.AsNoTracking().FirstOrDefault(k => k.CrmId == crmId && k.Type == (int)CrmuserInfoType.Financial && k.State == 2);
                    return crmUserInfo;
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 提交信息申请
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        /// <param name="loginName"></param>
        /// <param name="inputModels"></param>
        /// <returns></returns>
        public int SubmitUserInfo(int crmId, int type, List<InputModel> inputModels)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    CrmUserInfo crmUserInfo = new CrmUserInfo();
                    crmUserInfo.CrmId = crmId;
                    crmUserInfo.Type = type;
                    crmUserInfo.State = 0;
                    crmUserInfo.CreateDate = DateTime.Now;
                    if (type == (int)CrmuserInfoType.Personal)
                    {
                        crmUserInfo.Personal = inputModels.ToJson();
                    }
                    else if (type == (int)CrmuserInfoType.Financial)
                    {
                        crmUserInfo.Financial = inputModels.ToJson();
                    }
                    else if (type == (int)CrmuserInfoType.Identity)
                    {
                        crmUserInfo.Identity = inputModels.ToJson();
                    }
                    mtContext.CrmUserInfos.Add(crmUserInfo);
                    int count = mtContext.SaveChanges();
                    CrmAuditLog crmAuditLog = new CrmAuditLog()
                    {
                        OrderId = crmUserInfo.Id.ToString(),
                        CrmId = crmId,
                        Type = type,
                        Cont = "提交审核",
                        CreateDate = DateTime.Now
                    };
                    AddAuditLog(crmAuditLog);
                    return count;
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 提交信息申请
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        /// <param name="loginName"></param>
        /// <param name="inputModels"></param>
        /// <returns></returns>
        public int SubmitUserInfo(int crmId, int type, List<CrmKyc> inputModels)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    CrmUserInfo crmUserInfo = new CrmUserInfo();
                    crmUserInfo.CrmId = crmId;
                    crmUserInfo.Type = type;
                    crmUserInfo.State = 0;
                    crmUserInfo.CreateDate = DateTime.Now;
                    if (type == (int)CrmuserInfoType.Personal)
                    {
                        crmUserInfo.Personal = inputModels.ToJson();
                    }
                    else if (type == (int)CrmuserInfoType.Financial)
                    {
                        crmUserInfo.Financial = inputModels.ToJson();
                    }
                    else if (type == (int)CrmuserInfoType.Identity)
                    {
                        crmUserInfo.Identity = inputModels.ToJson();
                    }
                    mtContext.CrmUserInfos.Add(crmUserInfo);
                    int count = mtContext.SaveChanges();
                    CrmAuditLog crmAuditLog = new CrmAuditLog()
                    {
                        OrderId = crmUserInfo.Id.ToString(),
                        CrmId = crmId,
                        Type = type,
                        Cont = "提交审核",
                        CreateDate = DateTime.Now
                    };
                    AddAuditLog(crmAuditLog);
                    return count;
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        #region 修改信息

        /// <summary>
        ///  修改用户密码
        /// </summary>
        /// <param name="crmUser"></param>
        /// <returns></returns>
        public int UpdateCrmPassword(int crmId, string password)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    CrmUser crmUser = mtContext.CrmUsers.FirstOrDefault(k => k.Id == crmId);
                    crmUser.LoginPwd = password;
                    int count = mtContext.SaveChanges();
                    return count;
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        /// <summary>
        ///  修改交易密码
        /// </summary>
        /// <param name="crmUser"></param>
        /// <returns></returns>
        public int UpdateCrmTradePassword(int crmId, string tradePassword)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    CrmUser crmUser = mtContext.CrmUsers.FirstOrDefault(k => k.Id == crmId);
                    crmUser.TradePwd = tradePassword;
                    int count = mtContext.SaveChanges();
                    return count;
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        /// <summary>
        ///  修改用户密码
        /// </summary>
        /// <param name="crmUser"></param>
        /// <returns></returns>
        public int UpdateCrmPhone(int crmId, string phone)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    CrmUser crmUser = mtContext.CrmUsers.FirstOrDefault(k => k.Id == crmId);
                    crmUser.Telephone = phone;
                    int count = mtContext.SaveChanges();
                    return count;
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        /// <summary>
        ///  修改用户密码
        /// </summary>
        /// <param name="crmUser"></param>
        /// <returns></returns>
        public int UpdateCrmEmail(int crmId, string email)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    CrmUser crmUser = mtContext.CrmUsers.FirstOrDefault(k => k.Id == crmId);
                    crmUser.LoginName = email;
                    crmUser.Email = email;
                    int count = mtContext.SaveChanges();
                    return count;
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        #endregion

        #region 增加审核日志

        /// <summary>
        /// 下发审核日志
        /// </summary>
        /// <param name="crmAuditLog"></param>
        /// <returns></returns>
        public int  AddAuditLog(CrmAuditLog crmAuditLog)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    mtContext.CrmAuditLogs.Add(crmAuditLog);
                    int count = mtContext.SaveChanges();
                    return count;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        #endregion

    }
}
